package com.wuji.salary.controller;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.wuji.salary.entity.*;
import com.wuji.salary.service.AlgorithmService;
import com.wuji.salary.service.impl.AlgorithmServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import static com.wuji.salary.common.GetDingTalkAttendance.getAttendanceAll;

/**
 * 考勤数据对接
 */
@RestController
public class AttendanceController {


    /**
     *  传入日期
     */
    @GetMapping("/Attendance")
    public R attendance(String dateTime) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date date = format.parse(dateTime);
            delete(dateTime);
            add(dateTime);
            return R.ok();
        } catch (Exception e) {
            return R.fail("日期格式不正确");
        }
    }

    public static void main(String[] args) {
//        delete("2024-08-01 00:00:00");
//        add("dateTime");
    }


    /**
     * 新增考勤数据
     */
    public static void add(String dateTime) {
        ArrayList<Attendance> list = new ArrayList<>();
        AttendanceInfo attendanceInfo = new AttendanceInfo();
        /**
         * 从钉钉里取出数据进行复制
         */
        ArrayList<DingTalkAttendance> dingTalkAttendanceArrayList = getAttendanceAll(dateTime);
        for (DingTalkAttendance dingTalkAttendance : dingTalkAttendanceArrayList){
            Attendance attendance = new Attendance();
            BeanUtils.copyProperties(dingTalkAttendance, attendance);
            attendance.set_widget_1716735167931(dateTime);
            attendance.set_widget_1723089708217(dingTalkAttendance.getUserName());
            attendance.set_widget_1723089708234(dingTalkAttendance.getDeptName());
            attendance.set_widget_1716364600307(dingTalkAttendance.getJobNumber());
            attendance.setAppId("5569a94a7494bd67f1a8b5b6");
            attendance.setEntryId("59c204434e2c24e5fa5f2adb");
            list.add(attendance);
        }
        System.out.println(list);
        attendanceInfo.setDatas(list);
        System.out.println(attendanceInfo);
        /**
         * 去增加数据
         */
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonData = null;
        try {
            jsonData = objectMapper.writeValueAsString(attendanceInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }

        try {
            URL url = new URL("https://wjsz.online-office.net/openapi/v1/app/5569a94a7494bd67f1a8b5b6/entry/59c204434e2c24e5fa5f2adb/batch_data_create");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            connection.setRequestMethod("POST");  // 根据实际请求方法修改
            connection.setDoOutput(true);
            connection.setRequestProperty("Authorization", "Bearer GjkFIWKIupnYRI6rebU7sGxpPrMwuf4E");
            connection.setRequestProperty("Content-Type", "application/json");  // 设置为 JSON 格式

            // 将 JSON 数据发送
            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
            writer.write(jsonData);
            writer.flush();
            writer.close();

            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String line;
                StringBuilder response = new StringBuilder();
                while ((line = reader.readLine())!= null) {
                    response.append(line);
                }
                reader.close();
                System.out.println("Response: " + response.toString());
            } else {
                System.out.println("Error: " + responseCode);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    /**
     *  先去删除百数当前日期的考勤数据
     */
    public static void delete(String dateTime) {
        String jsonData = "{\n" +
                "  \"filter\": {\n" +
                "    \"rel\": \"and\",\n" +
                "    \"cond\": [\n" +
                "      {\n" +
                "        \"field\": \"_widget_1716735167931\",\n" +
                "        \"method\": \"eq\",\n" +
                "        \"value\": [\"" + dateTime + "\"]\n" +
                "      }\n" +
                "    ]\n" +
                "  }\n" +
                "}";
        try {
            URL url = new URL("https://wjsz.online-office.net/openapi/v1/app/5569a94a7494bd67f1a8b5b6/entry/59c204434e2c24e5fa5f2adb/data_batch_delete");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            connection.setRequestMethod("POST");  // 根据实际请求方法修改
            connection.setDoOutput(true);
            connection.setRequestProperty("Authorization", "Bearer GjkFIWKIupnYRI6rebU7sGxpPrMwuf4E");
            connection.setRequestProperty("Content-Type", "application/json");  // 设置为 JSON 格式

            // 将 JSON 数据发送
            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
            writer.write(jsonData);
            writer.flush();
            writer.close();

            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String line;
                StringBuilder response = new StringBuilder();
                while ((line = reader.readLine())!= null) {
                    response.append(line);
                }
                reader.close();
                System.out.println("Response: " + response.toString());
            } else {
                System.out.println("Error: " + responseCode);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
